// pages/settings/settings.ts
import { MerchantAPI } from '../../utils/api'

interface NotificationSettings {
  push_enabled: boolean;
  vibration_enabled: boolean;
  auto_sound_enabled: boolean;
  volume_level: number;
  ringtone: string;
  preorder_reminder_count: number;
  order_accept_reminder_count: number;
  new_order_reminder_count: number;
  auto_accept_order: boolean;
}

interface SettingsPageData {
  settings: NotificationSettings;
  loading: boolean;
  
  // 选择器选项
  reminderOptions: string[];
  ringtoneOptions: string[];
  
  // 铃声选择
  showRingtoneModal: boolean;
  selectedRingtone: string;
}

Page({
  data: {
    settings: {
      push_enabled: true,
      vibration_enabled: true,
      auto_sound_enabled: true,
      volume_level: 8,
      ringtone: "经典女声版",
      preorder_reminder_count: 3,
      order_accept_reminder_count: 3,
      new_order_reminder_count: 3,
      auto_accept_order: true
    },
    loading: false,
    
    // 选择器选项
    reminderOptions: ["1", "2", "3", "4", "5"],
    ringtoneOptions: [
      "经典女声版",
      "温柔男声版", 
      "活泼童声版",
      "商务提示音",
      "温馨提示音"
    ],
    
    // 铃声选择
    showRingtoneModal: false,
    selectedRingtone: "经典女声版"
  } as SettingsPageData,

  onLoad() {
    this.loadSettings();
  },

  /**
   * 加载设置信息
   */
  async loadSettings() {
    try {
      // 调用后端API获取当前设置：/merchant/notification-settings
      // const response = await MerchantAPI.getNotificationSettings();
      
      // 模拟设置数据
      const mockSettings = {
        push_enabled: true,
        vibration_enabled: true,
        auto_sound_enabled: true,
        volume_level: 8,
        ringtone: "经典女声版",
        preorder_reminder_count: 3,
        order_accept_reminder_count: 3,
        new_order_reminder_count: 3,
        auto_accept_order: true
      };
      
      this.setData({
        settings: mockSettings,
        selectedRingtone: mockSettings.ringtone
      });
      
    } catch (error) {
      console.error('加载设置失败:', error);
      wx.showToast({
        title: '加载设置失败',
        icon: 'none'
      });
    }
  },

  /**
   * 更新设置项
   */
  async updateSetting(e: any) {
    const key = e.currentTarget.dataset.key;
    const value = e.detail.value;
    
    const newSettings = {
      ...this.data.settings,
      [key]: value
    };
    
    this.setData({
      settings: newSettings
    });
    
    // 调用API保存设置
    this.saveSettings(newSettings);
  },

  /**
   * 更新音量
   */
  async updateVolume(e: any) {
    const volume = e.detail.value;
    
    const newSettings = {
      ...this.data.settings,
      volume_level: volume
    };
    
    this.setData({
      settings: newSettings
    });
    
    this.saveSettings(newSettings);
  },

  /**
   * 更新提醒次数
   */
  updateReminder(e: any) {
    const key = e.currentTarget.dataset.key;
    const index = e.detail.value;
    const count = parseInt(this.data.reminderOptions[index]);
    
    const newSettings = {
      ...this.data.settings,
      [key]: count
    };
    
    this.setData({
      settings: newSettings
    });
    
    this.saveSettings(newSettings);
  },

  /**
   * 保存设置到服务器
   */
  async saveSettings(settings: NotificationSettings) {
    try {
      // 调用后端API：/merchant/notification-settings
      // await MerchantAPI.updateNotificationSettings(settings);
      
      console.log('设置已保存:', settings);
      
    } catch (error) {
      console.error('保存设置失败:', error);
      wx.showToast({
        title: '设置保存失败',
        icon: 'none'
      });
    }
  },

  /**
   * 选择铃声
   */
  selectRingtone() {
    this.setData({
      showRingtoneModal: true,
      selectedRingtone: this.data.settings.ringtone
    });
  },

  /**
   * 选择铃声项
   */
  selectRingtoneItem(e: any) {
    const ringtone = e.currentTarget.dataset.ringtone;
    this.setData({
      selectedRingtone: ringtone
    });
  },

  /**
   * 试听铃声
   */
  playRingtone(e: any) {
    const ringtone = e.currentTarget.dataset.ringtone;
    wx.showToast({
      title: `正在试听 ${ringtone}`,
      icon: 'none'
    });
  },

  /**
   * 确认铃声选择
   */
  confirmRingtone() {
    const newSettings = {
      ...this.data.settings,
      ringtone: this.data.selectedRingtone
    };
    
    this.setData({
      settings: newSettings,
      showRingtoneModal: false
    });
    
    this.saveSettings(newSettings);
    
    wx.showToast({
      title: '铃声已更新',
      icon: 'success'
    });
  },

  /**
   * 应用推荐设置
   */
  async applyRecommended() {
    wx.showModal({
      title: '应用推荐设置',
      content: '将应用平台推荐的最佳设置配置，确定继续吗？',
      success: async (res) => {
        if (res.confirm) {
          this.setData({ loading: true });
          
          try {
            // 调用后端API：/merchant/notification-settings/recommended
            // const response = await MerchantAPI.applyRecommendedSettings();
            
            // 模拟推荐设置
            const recommendedSettings = {
              push_enabled: true,
              vibration_enabled: true,
              auto_sound_enabled: true,
              volume_level: 8,
              ringtone: "经典女声版",
              preorder_reminder_count: 3,
              order_accept_reminder_count: 3,
              new_order_reminder_count: 3,
              auto_accept_order: true
            };
            
            this.setData({
              settings: recommendedSettings
            });
            
            wx.showToast({
              title: '推荐设置应用成功',
              icon: 'success'
            });
            
          } catch (error) {
            wx.showToast({
              title: '应用设置失败',
              icon: 'none'
            });
          } finally {
            this.setData({ loading: false });
          }
        }
      }
    });
  },

  /**
   * 恢复默认设置
   */
  resetSettings() {
    wx.showModal({
      title: '恢复默认设置',
      content: '确定要恢复到默认设置吗？此操作不可撤销。',
      success: (res) => {
        if (res.confirm) {
          const defaultSettings = {
            push_enabled: true,
            vibration_enabled: false,
            auto_sound_enabled: false,
            volume_level: 5,
            ringtone: "经典女声版",
            preorder_reminder_count: 1,
            order_accept_reminder_count: 1,
            new_order_reminder_count: 1,
            auto_accept_order: false
          };
          
          this.setData({
            settings: defaultSettings
          });
          
          this.saveSettings(defaultSettings);
          
          wx.showToast({
            title: '已恢复默认设置',
            icon: 'success'
          });
        }
      }
    });
  },

  // 弹窗控制
  closeRingtoneModal() {
    this.setData({
      showRingtoneModal: false
    });
  },

  preventClose() {
    // 阻止事件冒泡
  }
});

